<template>
  <ul class="menu">
    <li v-for="(item, index) in menuData" :key="index">
      <div
        class="menu-item"
        @click="toggleSubMenu(index)"
        ref="menuItemRefs"
      >
        {{ item.label }}
        <span v-if="item.children && isSubMenuOpen[index]" class="icon-arrow-down"></span>
        <span v-if="item.children &&!isSubMenuOpen[index]" class="icon-arrow-right"></span>
      </div>
      <div
        v-show="item.children && isSubMenuOpen[index]"
        class="sub-menu-container"
        :style="{ left: computeSubMenuLeft(index) }"
      >
        <ul class="sub-menu">
          <MultiLevelMenu :menuData="item.children" />
        </ul>
      </div>
    </li>
  </ul>
</template>

<script>
import { ref, onMounted, nextTick } from 'vue';

export default {
  name: 'MultiLevelMenu',
  props: {
    menuData: {
      type: Array,
      required: true
    }
  },
  setup(props) {
    const isSubMenuOpen = ref([]);
    const menuItemRefs = ref([]);

    const toggleSubMenu = (index) => {
      if (!isSubMenuOpen.value[index]) {
        isSubMenuOpen.value[index] = true;
      } else {
        isSubMenuOpen.value[index] = false;
      }
    };

    const computeSubMenuLeft = (index) => {
      return `${menuItemRefs.value[index]?.$el.offsetWidth}px`;
    };

    onMounted(() => {
      // 确保 refs 在 DOM 更新后能获取到正确元素
      nextTick(() => {
        menuItemRefs.value = Array.from(document.querySelectorAll('.menu-item'));
      });
    });

    return {
      isSubMenuOpen,
      menuItemRefs,
      toggleSubMenu,
      computeSubMenuLeft
    };
  }
};
</script>

<style scoped>
.menu {
  list-style: none;
  padding: 0;
  margin: 0;
}

.menu-item {
  cursor: pointer;
  display: flex;
  align-items: center;
}

.sub-menu-container {
  position: absolute;
  top: 0;
  z-index: 1;
}

.sub-menu {
  list-style: none;
  padding-left: 20px;
}

.icon-arrow-down,
.icon-arrow-right {
  margin-left: 5px;
}
</style>